const express = require("express");
const { db } = require("../database");
const { CustomerAuth } = require("../middles");
const { validate, validators } = require("../validate");
const { pictures } = require("../upload");
const { query, findOne } = require("../logic");

const router = express.Router();
router.use(CustomerAuth);
router
  //添加分类
  .post(
    "/",
    pictures.single("picture"),
    validate([validators.parentId, validators.name, validators.description]),
    async (req, res) => {
      const { name, description, parent_id } = req.body;
      const exist = await db.findOne("select * from Category where name = ?", [
        name,
      ]);
      if (exist) return res.send({ success: false, message: "该分类已存在" });
      const results = await db.select(
        "insert into Category (name, picture, description, parent_id) values (?,?,?,?)",
        [
          name,
          "/pictures/" + req.file.filename,
          description,
          parent_id ? parent_id : null,
        ]
      );
      const category = await db.findOne("select * from Category where id = ?", [
        results.insertId,
      ]);
      res.send({ success: true, object: category });
    }
  )
  //修改分类
  .put(
    "/:id",
    pictures.single("picture"),
    validate([validators.parentId, validators.name, validators.description]),
    async (req, res) => {
      const { name, description, parent_id, picture } = req.body;
      let category = await db.findOne("select * from Category where id = ?", [
        req.params.id,
      ]);
      if (!category)
        return res.send({ success: false, message: "该分类不存在" });

      await db.query(
        "update Category set name = ?, description = ?, parent_id = ?, picture = ? where id = ?",
        [
          name,
          description,
          parent_id ? parent_id : null,
          picture ? picture : "/pictures/" + req.file.filename,
          req.params.id,
        ]
      );

      category = await db.findOne("select * from Category where id = ?", [
        req.params.id,
      ]);
      res.send({ success: true, object: category });
    }
  )
  //查看所有分类
  .get(
    "/",
    validate([validators.limit, validators.offset]),
    async (req, res) => {
      const { name } = req.query;
      const wheres = [],
        params = [];
      if (name) {
        wheres.push(`name like '%${name}%'`);
      }
      res.send({
        success: true,
        query: await query(
          req,
          "category a left join category b on a.parent_id = b.id",
          {
            fields: "a.*, json_array(a.parent_id, b.name) parent",
            wheres,
            params,
          }
        ),
      });
    }
  )
  // 外键查询
  .get("/fk", async (req, res) => {
    const { q } = req.query;
    const wheres = [`name like '%${q}%' or description like '%${q}%'`];
    res.send({
      success: true,
      query: await query(req, "Category", { wheres }),
    });
  })
  // 获取单个分类信息
  .get("/:id", async (req, res) => {
    res.send(await findOne(req.params.id, "Category"));
  });

//定义路由
const registerRouter = (app) => {
  app.use("/category", router);
};

module.exports = { registerRouter };
